/*
    KMC Simulation
    Copyright (c) 2012-2014 Filip Rozbořil

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "KmcSettings.h"
#include "Utils.h"
#include "includes.h"

KmcSettings :: KmcSettings()
{
	string line;	

	while(getline(cin, line))
	{
		// ignore blank lines and comments
		if(line.empty() || line[0] == '#')
			continue;
			
		// remove newlines and partial newlines to help fix issues with Windows formatted config files on Linux systems
		line.erase(remove(line.begin(), line.end(), '\r' ), line.end());
		line.erase(remove(line.begin(), line.end(), '\n' ), line.end());

		string::size_type split = line.find("=");
			
		Trace("[CONFIG] Split character '=' at: " + Utils::convertToString((int)split));

		if(split == string::npos)
		{
			throw Exception("Invalid KmcSettings entry '" + line + "'");
		}
		
		string::size_type keyStart = line.find_first_not_of(" \t");
		string::size_type keyEnd = line.find_last_not_of(" \t", split);
		string::size_type valueStart = line.find_first_not_of(" \t", split + 1);
		string::size_type valueEnd = line.size();

		if(valueStart != string::npos && keyEnd > keyStart)
		{
			string key = line.substr(keyStart, keyEnd - keyStart);
			string value = line.substr(valueStart, valueEnd - valueStart);
			Trace("[CONFIG] Adding pair {" + key + "} = " + value);
			mKeyToValue[key] = value;
		}
		else
		{
			throw Exception("Invalid KmcSettings entry '" + line + "'");
		}
	}
}

ostream& operator<<(ostream& os, KmcSettings& ks)
{
	for(auto i = ks.mKeyToValue.begin(); i != ks.mKeyToValue.end(); i++)
	{
		os << i->first << '=' << i->second << endl;
	}
	return os;
}
